package com.talkyun.openx.interceptor;

import org.springframework.util.AntPathMatcher;

import java.util.List;

public class AbstractSpringAntMatcher {
    private AntPathMatcher matcher = new AntPathMatcher();

    private List<String> patterns;
    private List<String> ignorePatterns;

    public void setPattern(List<String> ps) {
        this.patterns = ps;
    }

    public void setIgnorePattern(List<String> ps) {
        this.ignorePatterns = ps;
    }

    //    public void setSplitChar(String splitChar) {
    //        matcher.setPathSeparator(splitChar);
    //    }

    // 如果 path 不在 ignore pattern 且在 pattern，return true； other return false
    public boolean isMatched(String path) {
        if (this.isBlank(path)) {
            return false;
        }
        path = path.trim();

        // 1. ignore pattern check
        if (ignorePatterns != null && !ignorePatterns.isEmpty()) {
            for (String pattern : ignorePatterns) {
                if (this.isBlank(pattern)) {
                    continue;
                }
                if (this.isMatched(path, pattern.trim())) {
                    return false;
                }
            }
        }

        // 2. match pattern check
        if (patterns == null || patterns.isEmpty()) {
            return false;
        }
        for (String pattern : patterns) {
            if (this.isBlank(pattern)) {
                continue;
            }
            if (this.isMatched(path, pattern.trim())) {
                return true;
            }
        }

        // 3. last not match
        return false;
    }

    // xxx***xxx
    protected String toMaskString(String src, int begLen, int endLen) {
        int len = src == null ? 0 : src.length();
        if (len <= 1) {
            return "*";
        } else if (len < (begLen + endLen)) {
            return "***";
        }

        return src.substring(0, begLen) + "***" + src.substring(len - endLen);
    }

    protected boolean isMatched(String path, String pattern) {
        return matcher.match(pattern.toLowerCase(), path.toLowerCase());
    }

    protected boolean isBlank(String s) {
        return s == null || s.trim().length() == 0;
    }
}